// stores/category.js
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import categoryApi  from '@/api/category'

export const useCategoryStore = defineStore('category', () => {
  // 状态
  const categoryTree = ref([])
  const loading = ref(false)
  const activeTopLevelId = ref(0) // 默认选中"支出"
  const activeSecondLevelId = ref(null)

  // 计算属性
  const topLevelCategories = computed(() => {
    return Array.isArray(categoryTree.value) ? categoryTree.value : []
  })

  const activeTopLevel = computed(() => {
    if (!Array.isArray(topLevelCategories.value)) return null
    return topLevelCategories.value.find(cat => cat && cat.id === activeTopLevelId.value) || null
  })

  const activeSecondLevel = computed(() => {
    if (!activeTopLevel.value || !activeSecondLevelId.value) return null
    if (!Array.isArray(activeTopLevel.value.children)) return null
    return activeTopLevel.value.children.find(cat => cat && cat.id === activeSecondLevelId.value) || null
  })

  // 支出分类（快捷访问）
  const expenseCategories = computed(() => {
    const expense = categoryTree.value.find(cat => cat.name === '支出')
    return expense ? expense.children : []
  })

  // 收入分类（快捷访问）
  const incomeCategories = computed(() => {
    const income = categoryTree.value.find(cat => cat.name === '收入')
    return income ? income.children : []
  })

  // 转账分类（快捷访问）
  const transferCategories = computed(() => {
    const transfer = categoryTree.value.find(cat => cat.name === '转账')
    return transfer ? transfer.children : []
  })

  // 借贷分类（快捷访问）
  const loanCategories = computed(() => {
    const loan = categoryTree.value.find(cat => cat.name === '借贷')
    return loan ? loan.children : []
  })

  // 根据ID获取分类详情
  const getCategoryById = computed(() => (id) => {
    return findCategoryById(categoryTree.value, id)
  })

  // 递归查找分类
  const findCategoryById = (categories, id) => {
    for (const category of categories) {
      if (category.id === id) return category
      if (category.children && category.children.length > 0) {
        const found = findCategoryById(category.children, id)
        if (found) return found
      }
    }
    return null
  }

  // Actions
  const loadCategoryTree = async () => {
    loading.value = true
    try {
      const response = await categoryApi.getCategoryTree()
       categoryTree.value = response.data || []
      
      // 设置默认选中状态
      if (categoryTree.value.length > 0) {
        const expenseCategory = categoryTree.value.find(cat => cat.name === '支出')
        if (expenseCategory && expenseCategory.children.length > 0) {
          activeTopLevelId.value = expenseCategory.id
          activeSecondLevelId.value = expenseCategory.children[0].id
        }
      }
    } catch (error) {
      console.error('加载分类树失败:', error)
      // 使用默认数据作为fallback
      // categoryTree.value = getDefaultCategories()
    } finally {
      loading.value = false
    }
  }

  // 切换一级分类
  const setActiveTopLevel = (categoryId) => {
    activeTopLevelId.value = categoryId
    activeSecondLevelId.value = null
    
    // 如果有子分类，默认选中第一个
    const category = categoryTree.value.find(cat => cat.id === categoryId)
    if (category && category.children && category.children.length > 0) {
      activeSecondLevelId.value = category.children[0].id
    }
  }

  // 切换二级分类
  const setActiveSecondLevel = (categoryId) => {
    activeSecondLevelId.value = categoryId
  }

  // 重置选中状态
  const resetActiveCategories = () => {
    activeTopLevelId.value = 1
    activeSecondLevelId.value = null
  }

  // 默认分类数据（fallback）
  // const getDefaultCategories = () => {
  //   return [
  //     {
  //       id: 1,
  //       name: '支出',
  //       type: 0,
  //       parentId: 0,
  //       icon: 'expense',
  //       color: '#FF6B6B',
  //       sort: 1,
  //       children: [
  //         {
  //           id: 101,
  //           name: '购物消费',
  //           type: 0,
  //           parentId: 1,
  //           icon: 'shopping',
  //           color: '#FF9F43',
  //           sort: 1,
  //           children: [
  //             { id: 10101, name: '日常家具', type: 0, parentId: 101, icon: 'furniture', color: '#FF9F43', sort: 1 },
  //             { id: 10102, name: '个护美发', type: 0, parentId: 101, icon: 'beauty', color: '#FF9F43', sort: 2 }
  //           ]
  //         },
  //         {
  //           id: 102,
  //           name: '食品餐饮',
  //           type: 0,
  //           parentId: 1,
  //           icon: 'food',
  //           color: '#EE5A24',
  //           sort: 2,
  //           children: [
  //             { id: 10201, name: '早餐', type: 0, parentId: 102, icon: 'breakfast', color: '#EE5A24', sort: 1 },
  //             { id: 10202, name: '午餐', type: 0, parentId: 102, icon: 'lunch', color: '#EE5A24', sort: 2 },
  //             { id: 10203, name: '晚餐', type: 0, parentId: 102, icon: 'dinner', color: '#EE5A24', sort: 3 }
  //           ]
  //         }
  //       ]
  //     },
  //     {
  //       id: 2,
  //       name: '收入',
  //       type: 1,
  //       parentId: 0,
  //       icon: 'income',
  //       color: '#4ECDC4',
  //       sort: 2,
  //       children: [
  //         {
  //           id: 201,
  //           name: '工资收入',
  //           type: 1,
  //           parentId: 2,
  //           icon: 'salary',
  //           color: '#4ECDC4',
  //           sort: 1,
  //           children: [
  //             { id: 20101, name: '基本工资', type: 1, parentId: 201, icon: 'base-salary', color: '#4ECDC4', sort: 1 },
  //             { id: 20102, name: '绩效工资', type: 1, parentId: 201, icon: 'performance', color: '#4ECDC4', sort: 2 }
  //           ]
  //         }
  //       ]
  //     },
  //     {
  //       id: 3,
  //       name: '转账',
  //       type: 2,
  //       parentId: 0,
  //       icon: 'transfer',
  //       color: '#45B7D1',
  //       sort: 3,
  //       children: [
  //         { id: 301, name: '转出账户', type: 2, parentId: 3, icon: 'account-out', color: '#45B7D1', sort: 1 },
  //         { id: 302, name: '转入账户', type: 2, parentId: 3, icon: 'account-in', color: '#2D98DA', sort: 2 }
  //       ]
  //     },
  //     {
  //       id: 4,
  //       name: '借贷',
  //       type: 3,
  //       parentId: 0,
  //       icon: 'loan',
  //       color: '#96CEB4',
  //       sort: 4,
  //       children: []
  //     }
  //   ]
  // }

  return {
    // 状态
    categoryTree,
    loading,
    activeTopLevelId,
    activeSecondLevelId,
    
    // 计算属性
    topLevelCategories,
    activeTopLevel,
    activeSecondLevel,
    expenseCategories,
    incomeCategories,
    transferCategories,
    loanCategories,
    getCategoryById,
    
    // Actions
    loadCategoryTree,
    setActiveTopLevel,
    setActiveSecondLevel,
    resetActiveCategories
  }
})